package com.gjun.struts.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.management.RuntimeErrorException;

import org.apache.struts2.ServletActionContext;

import com.gjun.struts.bean.CategoryJsonBean;
import com.gjun.struts.bean.ext.Book;
import com.gjun.struts.bean.ext.Category;
import com.gjun.struts.resource.dao.IBookDao;
import com.gjun.struts.resource.dao.ICategoryDao;
import com.gjun.struts.util.JSONHelper;
import com.gjun.struts.util.UUIDGenerator;

public class SaveBooksAction {

	private int id;
	//book
	private int firstCategory;
	
	private int secondCategory;
	

	private String author;

	private String publishing;

	private String publishTime;
	
	private String wordNumber;

	private String whichEdtion;

	private String totalPage;

	private String printTime;

	private String printNumber;

	private String isbn;

	private String authorSummary;

	private String catalogue;
	
	//product
	private String productName;

	private String description;

	private long addTime;

	private double fixedPrice;

	private double dangPrice;

	private String keywords;

	private Integer hasDeleted;

	private String productPic;
	
	private File file;
	
	private String fileFileName;
	
	private String result;

	
	
	private IBookDao bookDao;
	
	private ICategoryDao categoryDao;
	
	
	private List<Category> categories;
	
	/**
	 * @return the categoryDao
	 */
	/**
	 * @return the firstCategory
	 */
	public int getFirstCategory() {
		return firstCategory;
	}
	
	/**
	 * @param firstCategory the firstCategory to set
	 */
	public void setFirstCategory(int firstCategory) {
		this.firstCategory = firstCategory;
	}
	
	/**
	 * @return the secondCategory
	 */
	public int getSecondCategory() {
		return secondCategory;
	}
	
	/**
	 * @param secondCategory the secondCategory to set
	 */
	public void setSecondCategory(int secondCategory) {
		this.secondCategory = secondCategory;
	}
	
	public ICategoryDao getCategoryDao() {
		return categoryDao;
	}

	/**
	 * @param categoryDao the categoryDao to set
	 */
	public void setCategoryDao(ICategoryDao categoryDao) {
		this.categoryDao = categoryDao;
	}

	/**
	 * @return the result
	 */
	public String getResult() {
		return result;
	}

	/**
	 * @param result the result to set
	 */
	public void setResult(String result) {
		this.result = result;
	}

	/**
	 * @return the fileFileName
	 */
	public String getFileFileName() {
		return fileFileName;
	}

	/**
	 * @param fileFileName the fileFileName to set
	 */
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	/**
	 * @return the bookDao
	 */
	public IBookDao getBookDao() {
		return bookDao;
	}

	/**
	 * @param bookDao the bookDao to set
	 */
	public void setBookDao(IBookDao bookDao) {
		this.bookDao = bookDao;
	}

	/**
	 * @return the file
	 */
	public File getFile() {
		return file;
	}

	/**
	 * @param file the file to set
	 */
	public void setFile(File file) {
		this.file = file;
	}


	/**
	 * @return the author
	 */
	public String getAuthor() {
		return author;
	}

	/**
	 * @param author the author to set
	 */
	public void setAuthor(String author) {
		this.author = author;
	}

	/**
	 * @return the publishing
	 */
	public String getPublishing() {
		return publishing;
	}

	/**
	 * @param publishing the publishing to set
	 */
	public void setPublishing(String publishing) {
		this.publishing = publishing;
	}

	/**
	 * @return the publishTime
	 */
//	public long getPublishTime() {
//		return publishTime;
//	}
	public String getPublishTime() {
		return publishTime;
	}

	/**
	 * @param publishTime the publishTime to set
	 */
//	public void setPublishTime(long publishTime) {
//		this.publishTime = publishTime;
//	}
	public void setPublishTime(String publishTime) {
		this.publishTime = publishTime;
	}


	/**
	 * @return the wordNumber
	 */
	public String getWordNumber() {
		return wordNumber;
	}

	/**
	 * @param wordNumber the wordNumber to set
	 */
	public void setWordNumber(String wordNumber) {
		this.wordNumber = wordNumber;
	}

	/**
	 * @return the whichEdtion
	 */
	public String getWhichEdtion() {
		return whichEdtion;
	}

	/**
	 * @param whichEdtion the whichEdtion to set
	 */
	public void setWhichEdtion(String whichEdtion) {
		this.whichEdtion = whichEdtion;
	}

	/**
	 * @return the totalPage
	 */
	public String getTotalPage() {
		return totalPage;
	}

	/**
	 * @param totalPage the totalPage to set
	 */
	public void setTotalPage(String totalPage) {
		this.totalPage = totalPage;
	}

	/**
	 * @return the printTime
	 */
	public String getPrintTime() {
		return printTime;
	}

	/**
	 * @param printTime the printTime to set
	 */
	public void setPrintTime(String printTime) {
		this.printTime =  printTime;
		
	}

	/**
	 * @return the printNumber
	 */
	public String getPrintNumber() {
		return printNumber;
	}

	/**
	 * @param printNumber the printNumber to set
	 */
	public void setPrintNumber(String printNumber) {
		this.printNumber = printNumber;
	}

	/**
	 * @return the isbn
	 */
	public String getIsbn() {
		return isbn;
	}

	/**
	 * @param isbn the isbn to set
	 */
	public void setIsbn(String isbn) {
		this.isbn = isbn;
	}

	/**
	 * @return the authorSummary
	 */
	public String getAuthorSummary() {
		return authorSummary;
	}

	/**
	 * @param authorSummary the authorSummary to set
	 */
	public void setAuthorSummary(String authorSummary) {
		this.authorSummary = authorSummary;
	}

	/**
	 * @return the catalogue
	 */
	public String getCatalogue() {
		return catalogue;
	}

	/**
	 * @param catalogue the catalogue to set
	 */
	public void setCatalogue(String catalogue) {
		this.catalogue = catalogue;
	}

	/**
	 * @return the productName
	 */
	public String getProductName() {
		return productName;
	}

	/**
	 * @param productName the productName to set
	 */
	public void setProductName(String productName) {
		this.productName = productName;
	}

	/**
	 * @return the description
	 */
	public String getDescription() {
		return description;
	}

	/**
	 * @param description the description to set
	 */
	public void setDescription(String description) {
		this.description = description;
	}

	/**
	 * @return the addTime
	 */
	public long getAddTime() {
		return addTime;
	}

	/**
	 * @param addTime the addTime to set
	 */
	public void setAddTime(long addTime) {
		this.addTime = addTime;
	}

	/**
	 * @return the fixedPrice
	 */
	public double getFixedPrice() {
		return fixedPrice;
	}

	/**
	 * @param fixedPrice the fixedPrice to set
	 */
	public void setFixedPrice(double fixedPrice) {
		this.fixedPrice = fixedPrice;
	}

	/**
	 * @return the dangPrice
	 */
	public double getDangPrice() {
		return dangPrice;
	}

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}

	/**
	 * @param dangPrice the dangPrice to set
	 */
	public void setDangPrice(double dangPrice) {
		this.dangPrice = dangPrice;
	}

	/**
	 * @return the keywords
	 */
	public String getKeywords() {
		return keywords;
	}

	/**
	 * @param keywords the keywords to set
	 */
	public void setKeywords(String keywords) {
		this.keywords = keywords;
	}

	/**
	 * @return the hasDeleted
	 */
	public Integer getHasDeleted() {
		return hasDeleted;
	}

	/**
	 * @param hasDeleted the hasDeleted to set
	 */
	public void setHasDeleted(Integer hasDeleted) {
		this.hasDeleted = hasDeleted;
	}

	/**
	 * @return the productPic
	 */
	public String getProductPic() {
		return productPic;
	}

	/**
	 * @param productPic the productPic to set
	 */
	public void setProductPic(String productPic) {
		this.productPic = productPic;
	}
	
	
	private static void copy(File src, File dst) {
		try {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = new BufferedInputStream(new FileInputStream(src));
				out = new BufferedOutputStream(new FileOutputStream(dst));
				byte[] buffer = new byte[1024];
				while (in.read(buffer) > 0) {
					out.write(buffer);
				}
			} finally {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String saveBook() {
//		System.out.println("============================:  " + fileFileName);
//		System.out.println("前缀:      " + getExtention(fileFileName));
//		System.out.println("----------------------------:  " + info);
//		System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&:  " + typename);
		
		Book book = new Book();
		try{
			book.setId(bookDao.getLastId());
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		book.setAddTime(System.currentTimeMillis());
		book.setProductName(productName);
		book.setDescription(description);
		book.setAddTime(System.currentTimeMillis());
		book.setFixedPrice(fixedPrice);
		book.setDangPrice(dangPrice);
		book.setKeywords(keywords);
		book.setPrintNumber(printNumber);
		book.setHasDeleted(0);
		
		
		book.setAuthor(author);
		book.setPublishing(publishing);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD");
		try {
			book.setPublishTime(sdf.parse(publishTime).getTime());
			if(printTime!= null)
				book.setPrintTime((int)sdf.parse(printTime).getTime());
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		
		book.setWordNumber(wordNumber);
		book.setWhichEdtion(whichEdtion);
		book.setTotalPage(totalPage);
		book.setIsbn(isbn);
		book.setAuthorSummary(authorSummary);
		book.setCatalogue(catalogue);
		
		
		if(file!=null){
			String fileName = new UUIDGenerator().generate().toString()
					+ getExtention(fileFileName);
			
			String fileSavePath = ServletActionContext.getRequest()
					.getRealPath("/")
					+ "newsImage\\" + fileName;
			//System.out.println(ServletActionContext.getRequest().getContextPath()+"/newsImage/"+fileName);
			copy(file,new File(fileSavePath));
	
			book.setProductPic(ServletActionContext.getRequest().getContextPath()+"/newsImage/"+fileName);
		}
		try {
			bookDao.saveBook(book);
			result = "saveSuccess"; 
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = "saveFaild";
		}

		return "success";
	}
	
	private static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);
	}
	
	
	public String loadFirstCategory(){
		categories = categoryDao.findAllCategory();
		try {
			List<CategoryJsonBean> list = new ArrayList<CategoryJsonBean>();
			for (Category category:categories) {
				CategoryJsonBean tempt = new CategoryJsonBean(category.getId(),category.getName());
				list.add(tempt);
			}
			result = JSONHelper.categoryToJson(list);
			System.out.println(result);
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "success"; 
	}
	
	public String loadSecondCategory(){
		System.out.println(categories);
		categories = categoryDao.findAllCategory();
		List<CategoryJsonBean> list = new ArrayList<CategoryJsonBean>();
		for (Category category : categories) {
			if(category.getId() == firstCategory){
				Set<Category> lists = category.getSubCats();
				for (Category category2 : lists) {
					CategoryJsonBean tempt = null;
						
					tempt = new CategoryJsonBean(category2.getId(),category2.getName());
					
					list.add(tempt);
				}
				break;
			}
		}
		try {
			result = JSONHelper.categoryToJson(list);
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
		return "success";
	}
	
	public String updateNewsContent(){
		if(id==0){
			return "updatesFaild"; 
		}
		Book book = bookDao.getBookById(id);
		book.setProductName(productName);
		book.setDescription(description);
		book.setAddTime(System.currentTimeMillis());
		book.setFixedPrice(fixedPrice);
		book.setDangPrice(dangPrice);
		book.setKeywords(keywords);
		book.setPrintNumber(printNumber);
		book.setHasDeleted(0);
		
		
		book.setAuthor(author);
		book.setPublishing(publishing);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD");
		try {
			book.setPublishTime(sdf.parse(publishTime).getTime());
			if(printTime!= null)
				book.setPrintTime((int)sdf.parse(printTime).getTime());
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		
		book.setWordNumber(wordNumber);
		book.setWhichEdtion(whichEdtion);
		book.setTotalPage(totalPage);
		book.setIsbn(isbn);
		book.setAuthorSummary(authorSummary);
		book.setCatalogue(catalogue);
		
		
		if(file!=null){
			String fileName = new UUIDGenerator().generate().toString()
					+ getExtention(fileFileName);
			
			String fileSavePath = ServletActionContext.getRequest()
					.getRealPath("/")
					+ "newsImage\\" + fileName;
			//System.out.println(ServletActionContext.getRequest().getContextPath()+"/newsImage/"+fileName);
			copy(file,new File(fileSavePath));
	
			book.setProductPic(ServletActionContext.getRequest().getContextPath()+"/newsImage/"+fileName);
		}
		try {
			bookDao.updateBook(book);
			result = "updateSuccess"; 
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = "updateFaild";
		}

		return "success";
	}
	
	public String execute(){
		return "success";
	}
		
}
